import advListView from '$v/advList'
// import e from 'express'

//权限管理
import {
  isLoginRequest
} from '../api/admin'

//引入接口
import {
  addAdvRequest,
  advListRequest,
  deleteAdvRequest,
  getUpdateAdvRequest,
  updateAdvRequest
} from "../api/adv"

//封装一个函数获取数据库的广告列表进行渲染
const getAllAdvList = async (res) => {
  //发送请求
  try {
    return await advListRequest()
  } catch (e) {
    alert("列表获取异常", e.message)
    //判断是否是权限异常
    if (!e.isLogin) {
      return router.go("/login");
    }
  }
}

export default async (req, res) => {
  //路由切换的时候验证登录
  try {
    await isLoginRequest();
  } catch (e) {
    //请求异常后提示用户
    alert("有异常" + e.message)

    //判断是否是权限异常
    if (!e.isLogin) {
      return router.go("/login");
    }
  }

  const { advList, allPageCount } = await getAllAdvList()
  // console.log(advList);
  res.render(advListView({
    advList,
    allPageCount
  }))
  // res.render(advListView())

  //事件委派
  document.onclick = async function (e) {
    // console.log("e.target.id",e.target.id);
    //添加广告逻辑
    if (e.target.id === "adv-save") {
      //使用node内置方法FormData收集表单数据
      const myForm = new FormData(document.advForm)
      // console.log("FormData",myForm);
      // console.log(myForm.get("advTitle"));
      // console.log(myForm.get("advType"));
      // console.log(myForm.get("advOrder"));
      // console.log(myForm.get("advPic"));//file对象
      //判空
      if (!myForm.get("advTitle") || !myForm.get("advType") || !myForm.get("advOrder") || !myForm.get("advPic")) {
        return alert("添加的内容不能有空的!!!")
      }

      //发送请求
      try {
        await addAdvRequest(myForm)
        alert("添加广告成功")
        //关闭添加广告的弹窗
        document.getElementById("addClose").click();

        //把预览的img隐藏，否则下一次更新时，预览发图片仍在预览处
        const oPreImg = document.getElementById('preImg');
        oPreImg.style.display = "none"

        //清空表单
        document.advForm.reset();
        //重新渲染图片
        const { advList, allPageCount } = await getAllAdvList()
        // console.log(advList);
        res.render(advListView({
          advList,
          allPageCount
        }))
        // console.log(advList);
        res.render(advListView({ advList }))
      } catch (e) {
        alert("添加广告异常" + e.message);
        //判断是否是权限异常
        if (!e.isLogin) {
          //关闭添加广告的弹窗再跳转
          document.getElementById("addClose").click();
          return router.go("/login");
        }
      }
    }

    //广告删除逻辑
    // console.log(e.target.classList.contains("btn-delete"));
    if (e.target.nodeName === "BUTTON" && e.target.classList.contains("btn-delete")) {
      // console.log(e.target.classList);
      //把id保存在自定义属性中
      const _id = e.target.dataset.id
      // console.log(_id);//upload/6e245b8fe4a5a222512a18c00.png
      try {

        await deleteAdvRequest(_id)
        //重新获取列表进行渲染
        // alert("2")
        const { advList, allPageCount } = await getAllAdvList()
        // console.log(advList);
        res.render(advListView({
          advList,
          allPageCount
        }))
        // alert("3")
      } catch (e) {
        alert("删除数据失败" + e.message)

        //判断是否是权限问题
        if (!e.isLogin) {
          //关闭添加广告的弹窗再跳转
          document.getElementById("addClose").click();
          return router.go("/login");
        }
      }
    }

    //点击更新按钮获取当前按钮对应的广告信息(图片除外)逻辑
    if (e.target.nodeName === "BUTTON" && e.target.classList.contains("btn-update")) {
      //获取id值
      const _id = e.target.dataset.id
      //发送请求,将id值传给后端进行查询
      try {
        const updateData = await getUpdateAdvRequest(_id)
        //把数据放入到更新的窗口中
        document.advUpdate.advTitle.value = updateData.advTitle
        document.advUpdate.advType.value = updateData.advType
        document.advUpdate.advOrder.value = updateData.advOrder
        // document.advUpdate.advPic.value = updateData.advPic
        //在点击弹窗外的更新时已经获取到当前广告的所有信息
        document.getElementById("adv-update").dataset.id = updateData._id
      } catch (e) {
        alert("更新查询失败" + e.message)
      }
    }

    //点击弹框上的更新,修改并更新当前广告数据
    if (e.target.id === "adv-update") {
      const _id = e.target.dataset.id
      // console.log("_id",_id);//62c12b465c5f45c49fdec8f2
      //收集表单数据,使用formData
      const myForm = new FormData(document.advUpdate)
      console.log("FormData", myForm);
      console.log(myForm.get("advTitle"));
      console.log(myForm.get("advType"));
      console.log(myForm.get("advOrder"));
      console.log(myForm.get("advPic"));

      //判空
      if (!myForm.get("advTitle") || !myForm.get("advType") || !myForm.get("advOrder") || !myForm.get("advPic")) {
        return alert("添加的内容不能有空的!!!")
      }

      try {
        await updateAdvRequest(myForm, _id)

        alert("广告列表更新成功")

        // document.getElementById("modal-update").style.display = 'none'
        //重新渲染图片
        // const advList = await getAllAdvList()
        // res.render(advListView({ advList }))

        const { advList, allPageCount } = await getAllAdvList()
        // console.log(advList);
        res.render(advListView({
          advList,
          allPageCount
        }))
      } catch (e) {
        // document.getElementById("modal-update").style.display = 'none'
        alert("广告列表更新失败")
        //判断是否是权限异常
        if (!e.isLogin) {
          //关闭添加广告的弹窗再跳转
          document.getElementById("addClose").click();
          return router.go("/login");
        }
      }
    }


    //onchange在表单的状态改变并失去焦点时生效
    document.onchange = function (e) {
      console.log("onchange", e);
      if (e.target.id === "advPic") {
        //FileReader
        const reader = new FileReader()
        //e.target.files返回的是文件信息组成的一个数组
        console.log("files", e.target.files);
        reader.readAsDataURL(e.target.files[0])
        reader.onload = function (e) {
          // console.log("onload",e);
          const oPreImg = document.getElementById('preImg');
          const oPreImg1 = document.getElementById('preImg1');
          oPreImg.src = e.target.result;////base64格式的图片地址
          oPreImg1.src = e.target.result;
          oPreImg.style.display = "block"
          oPreImg1.style.display = "block"
        }
        // addAdvRequest(myForm)
      }
    }
  }
}